package com.miaosha.controller;

import com.miaosha.entity.MiaoShaGoods;
import com.miaosha.entity.Order;
import com.miaosha.service.MiaoShaGoodsService;
import com.miaosha.service.OrderService;
import com.miaosha.utils.CommonResult;
import com.miaosha.utils.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/miaoShaGoods")
public class MiaoShaGoodsController {

    @Resource
    private MiaoShaGoodsService miaoShaGoodsService;

    @Resource
    private OrderService orderService;

    @Autowired
    JwtTokenUtil jwtTokenUtil;

    @Autowired
    HttpServletRequest request;

    @GetMapping("/listAllNow")
    public List<MiaoShaGoods> listAllNow() {

        List<MiaoShaGoods> miaoShaGoodsList = miaoShaGoodsService.listAllNow();

        log.info("秒杀商品：{}", miaoShaGoodsList.size());

        String token = request.getHeader("Authorization").substring(7);

        Long userId = jwtTokenUtil.getUserIdFromToken(token);

        log.info("userId: {}", userId);

        //已经抢到的秒杀商品不能查看
        for (int i = 0; i < miaoShaGoodsList.size(); i++) {
            MiaoShaGoods miaoShaGoods = miaoShaGoodsList.get(i);
            Map<String, Object> map = new HashMap<>(16);
            map.put("userId", userId);
            map.put("miaoShaGoodsId", miaoShaGoods.getId());
            Order order = orderService.findByUserIdAndMiaoShaGoodsId(map);
            //已经秒杀过就不显示这个商品
            if (order != null) {
                miaoShaGoodsList.remove(miaoShaGoods);
                i--;
            }
        }
        return miaoShaGoodsList;
    }

    @GetMapping("/findById/{id}")
    public MiaoShaGoods findById(@PathVariable Integer id) {
        return miaoShaGoodsService.findById(id);
    }

    @GetMapping("/findByName/{name}")
    public MiaoShaGoods findByName(@PathVariable Integer id) {
        return miaoShaGoodsService.findById(id);
    }

    @PostMapping("/addMiaosha")
    @Transactional
    public CommonResult addMiaosha(@Validated @RequestBody MiaoShaGoods miaoShaGood) {
        miaoShaGoodsService.save(miaoShaGood);
        miaoShaGoodsService.add2Redis(miaoShaGood);
        return CommonResult.success(null);
    }
}
